package com.zcyr.service;

import com.zcyr.core.AbstractDatabaseEnvironment;
import com.zcyr.core.impl.CommandExecutor;
import com.zcyr.exception.CommandExecutorException;
import com.zcyr.exception.DatabaseEnvironmentException;
import com.zcyr.exception.TrymeUserSQLException;
import com.zcyr.pojo.SQLResult;
import com.zcyr.util.JsonBody;
import com.zcyr.util.SQLTrim;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

@Service
public class DemoService {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    CommandExecutor commandExecutor;

    private boolean checkIsCommand(String code){
        return code.trim().charAt(0) == '\\';
    }

    public JsonBody wrapSQLResult(SQLResult result){
        JsonBody body = JsonBody.ok();
        body.put("type", result.type);
        body.put("updateCount", result.updateCount);
        body.put("time_consuming", result.getTime_consuming());
        body.put("metaData", result.meteData);
        body.put("data", result.tableData);
        return body;
    }

    public JsonBody executeSQL(AbstractDatabaseEnvironment environment, String sql) throws SQLException, DatabaseEnvironmentException, CommandExecutorException {
        Date date;
        SQLResult result;
        if (checkIsCommand(sql)){
            date = new Date();
            result = commandExecutor.executeCommand(sql, environment);
            result.setTime_consuming(new Date().getTime() - date.getTime());
            return wrapSQLResult(result);
        }
        try{
            List<SQLResult> results = environment.executeSQL(sql);
            return wrapSQLResult(results.get(results.size() - 1));
        } catch (TrymeUserSQLException e){
            logger.info("用户环境sql执行异常, 环境: " + environment + " SQLException: " + e.getMessage());
            throw new TrymeUserSQLException(SQLTrim.removeSuffix(e.getMessage(), environment.getUuid()));
        }
    }
}
